﻿using System;
using System.Configuration;
using System.Data.SqlClient;

public partial class OnlyAuthenticated_OnlyManagers_EditSpecialitati : System.Web.UI.Page
{
    private readonly SqlConnection _connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString);
    
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        string remove;
        int nrItems = ListBox1.Items.Count;

        for (int i = 0; i < nrItems; i++)
        {
            if (ListBox1.Items[i].Selected)
            {
                remove = ListBox1.Items[i].Value;
                DeleteRecord(remove);
            }
        }

        ListBox1.DataBind();
    }


    private void DeleteRecord(string NumeSpecialitate)
    {
        string sqlStatement = "DELETE FROM DenumiriSpecialitati WHERE NumeSpecialitate = @NumeSpecialitate";

        try
        {
            _connection.Open();
            SqlCommand cmd = new SqlCommand(sqlStatement, _connection);
            cmd.Parameters.AddWithValue("@NumeSpecialitate", NumeSpecialitate);
            cmd.ExecuteNonQuery();
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Delete Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            _connection.Close();
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        InsertRecord(TextBox1.Text);
        TextBox1.Text = string.Empty;
        ListBox1.DataBind(); //rebind
    }

    private void InsertRecord(string NumeSpecialitate)
    {
        string sqlStatement = "IF NOT EXISTS (SELECT NumeSpecialitate FROM DenumiriSpecialitati WHERE NumeSpecialitate = @NumeSpecialitate) BEGIN INSERT INTO DenumiriSpecialitati (NumeSpecialitate) VALUES (@NumeSpecialitate) END";
        try
        {
            _connection.Open();
            SqlCommand cmd = new SqlCommand(sqlStatement, _connection);
            cmd.Parameters.AddWithValue("@NumeSpecialitate", NumeSpecialitate);
            cmd.ExecuteNonQuery();
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            _connection.Close();
        }
    }

    protected void Button3_Click(object sender, EventArgs e)
    {
        ListBox1.DataBind();
    }
}